package com.fastloan.jn.mgt.customermanager.weekly.service.impl;

import com.fastloan.jn.common.BasicServiceImpl;
import com.fastloan.jn.mgt.common.util.DateTimeUtil;
import com.fastloan.jn.mgt.common.util.excelutil.ExcelDateUtil;
import com.fastloan.jn.mgt.customermanager.basic.model.JnCustomerManager;
import com.fastloan.jn.mgt.customermanager.basic.service.JnCustomerManagerService;
import com.fastloan.jn.mgt.customermanager.daily.model.JnCustomerManagerDaily;
import com.fastloan.jn.mgt.customermanager.daily.service.JnCustomerManagerDailyService;
import com.fastloan.jn.mgt.customermanager.weekly.dao.JnCustomerManagerWeeklyMapper;
import com.fastloan.jn.mgt.customermanager.weekly.model.JnCustomerManagerWeekly;
import com.fastloan.jn.mgt.customermanager.weekly.model.vo.ManagerWeeklyExt;
import com.fastloan.jn.mgt.customermanager.weekly.service.JnCustomerManagerWeeklyService;
import com.fastloan.safe.mgt.user.model.CmuUser;
import com.fastloan.safe.mgt.user.service.CmuUserService;
import com.kawins.supers.table.manager.DataTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author yanwe
 *         createTime 2017-10-2017/10/19 16:30
 */
@Service
public class JnCustomerManagerWeeklyServiceImpl extends BasicServiceImpl<JnCustomerManagerWeekly> implements JnCustomerManagerWeeklyService {

    @Autowired
    private JnCustomerManagerService jnCustomerManagerService;

    @Autowired
    private JnCustomerManagerDailyService jnCustomerManagerDailyService;

    @Autowired
    private CmuUserService cmuUserService;

    @Autowired
    private JnCustomerManagerWeeklyMapper weeklyMapper;


    @Override
    @Transactional
    public void initWeekly() {
        LocalDateTime now = LocalDateTime.now();
        List<String> needInitUserIdList = selectNeedUser(now);//查询需要生成的用户
        createWeekly(needInitUserIdList, now);//生成周报和日报
    }

    @Override
    @DataTable(name = "managerWeekLyExts")
    public List<ManagerWeeklyExt> managerWeekLyExts(Map<String, Object> map) {
        return weeklyMapper.managerWeeklyExts(map);
    }


    private List<String> selectNeedUser(LocalDateTime now) {
        List<JnCustomerManager> allManager = jnCustomerManagerService.selectAll();
        LocalDateTime[] weekDay = ExcelDateUtil.getWeekDay(now);
        String monday = weekDay[0].format(DateTimeFormatter.ISO_DATE);
        Example example = new Example(JnCustomerManagerWeekly.class);
        return allManager.stream()
                .map(JnCustomerManager::getUserId)
                .filter(userId -> {
                    example.createCriteria()
                            .andEqualTo("userId", userId)
                            .andCondition("TO_CHAR (JN_CUSTOMER_MANAGER_WEEKLY.CREATE_TIME,'YYYY-MM-DD')" +
                                    " = '" + monday + "'");
                    List<JnCustomerManagerWeekly> jnCustomerManagerWeeklies = selectByExample(example);
                    example.clear();
                    return jnCustomerManagerWeeklies.size() == 0;
                }).collect(Collectors.toList());
    }

    private void createWeekly(List<String> needInitUserIdList, LocalDateTime time) {
        LocalDateTime[] weekDay = ExcelDateUtil.getWeekDay(time);
        String monday = weekDay[0].format(DateTimeFormatter.ISO_DATE);
        String friday = weekDay[4].format(DateTimeFormatter.ISO_DATE);
        CmuUser cmuUser = new CmuUser();
        needInitUserIdList.parallelStream().forEach(userId -> {
            cmuUser.setId(userId);
            String userName = cmuUserService.selectOne(cmuUser).getUsername();
            JnCustomerManagerWeekly jnCustomerManagerWeekly = JnCustomerManagerWeekly
                    .JnCustomerManagerWeeklyBuilder.aJnCustomerManagerWeekly()
                    .withCreateTime(DateTimeUtil.localDate2DateTime(weekDay[0]))
                    .withUserId(userId)
                    .withWeeklyName(userName + "(" + monday + "到" + friday + ")周报")
                    .build();
            insertSelective(jnCustomerManagerWeekly);
            Stream.of(weekDay).parallel()
                    .map(day -> JnCustomerManagerDaily.JnCustomerManagerDailyBuilder.aJnCustomerManagerDaily()
                            .withUserId(userId)
                            .withWeeklyId(jnCustomerManagerWeekly.getWeeklyId())
                            .withWeekday(day.getDayOfWeek().getValue())
                            .withCreateTime(DateTimeUtil.localDate2DateTime(day)).build())
                    .forEach(jnCustomerManagerDailyService::insertSelective);
        });
    }

}
